package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrAttrgroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Resource
    private AttrGroupDao attrGroupDao;
    @Resource
    private CategoryDao categoryDao;
    @Resource
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttrEntity(AttrVo attrVo) {
        // 1. 保存attrEntity
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        // 2. 保存关联关系表属性分组id attrGroupId
        if (attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    /**
     * 2、获取分类规格参数的基本分页信息
     *
     * @param params
     * @param catelogId
     * @return
     */
    @Override
    public PageUtils queryBaseListAttrPage(Map<String, Object> params, Long catelogId) {
        // 模糊查询
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        // 获取参数请求 检锁条件
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        // 分页数据
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        // 把生成的Ipage对象封装到pageUtils里
        PageUtils pageUtils = new PageUtils(page);
        // 查询新增属性 从Ipage对象获取记录
        List<AttrEntity> records = page.getRecords();
        // 处理返回页面的数据
        List<AttrRespVo> attrRespVoList = records.stream().map(attrEntity -> {
            // 创建AttrRespVo响应前端的对象
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 设置分类的名字
            CategoryEntity categoryEntity = categoryDao.selectOne(
                    new QueryWrapper<CategoryEntity>().eq("cat_id", attrEntity.getCatelogId())
            );
            if (ObjectUtils.isNotEmpty(categoryEntity)) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            // 设置分组名字
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId())
            );
            if (ObjectUtils.isNotEmpty(attrAttrgroupRelationEntity)
                    && ObjectUtils.isNotEmpty(attrAttrgroupRelationEntity.getAttrGroupId())) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>()
                        .eq("attr_group_id", attrAttrgroupRelationEntity.getAttrGroupId()));
                if (ObjectUtils.isNotEmpty(attrGroupEntity)) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            // 处理封装好数据返回
            return attrRespVo;
        }).collect(Collectors.toList());

        // 将处理的数据封装给分页工具
        pageUtils.setList(attrRespVoList);
        // 返回分页数据
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        // 创建返回页面的响应对象
        AttrRespVo attrRespVo = new AttrRespVo();
        // 数据库查询实体类
        AttrEntity attrEntity = this.getById(attrId);
        // 拷贝基本属性
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        // 设置分组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId)
            );
            if (ObjectUtils.isNotEmpty(attrAttrgroupRelationEntity)) {
                attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (ObjectUtils.isNotEmpty(attrGroupEntity)) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        // 设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (ObjectUtils.isNotNull(categoryEntity)) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        // 返回数据
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attrVo) {
        // 1.创建对象接收前端传来的vo对象
        AttrEntity attrEntity = new AttrEntity();
        // 2. 赋值属性
        BeanUtils.copyProperties(attrVo, attrEntity);
        // 3. 先更新自己的表pms_attr
        this.updateById(attrEntity);
        // 4. 如果是基本属性进行修改
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 修改分组关联 pms_attr_attrgroup_relation
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrVo.getAttrId());
            // 判断数据库是否有relationEntity 有了更新 没有则添加
            Integer count = attrAttrgroupRelationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            if (ObjectUtils.isNotNull(count)) {
                attrAttrgroupRelationDao.update(
                        relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 平台属性 可以通过在添加路径变量{attrType}同时用一个方法查询销售属性和规格参数
     * 注意：销售属性，没有分组信息，所以复用方法的时候，要判断是销售属性还是规格参数
     *
     * @param params
     * @param catelogId
     * @param attrType
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        // 创建查询对象
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(attrType) ? 1 : 0);
        // 如果catelogId有值进行拼接
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        // 获取关键字进行模糊匹配key 如果有值接着组装查询条件
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key).or().like("icon", key);
            });
        }
        // 封装分页查询
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        // 重新分页工具返回给前端更丰富的数据
        PageUtils pageUtils = new PageUtils(page);
        // 获取分页数据记录
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> collectAttrRespVoList = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 设置属性分组关联的名字
            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (ObjectUtils.isNotNull(attrAttrgroupRelationEntity)) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectOne(
                            new QueryWrapper<AttrGroupEntity>()
                                    .eq("attr_group_id", attrAttrgroupRelationEntity.getAttrGroupId())
                    );
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            // 设置三级分类的名字
            CategoryEntity categoryEntity = categoryDao.selectOne(new QueryWrapper<CategoryEntity>()
                    .eq("cat_id", attrEntity.getCatelogId()));
            if (ObjectUtils.isNotNull(categoryEntity)) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            return attrRespVo;
        }).collect(Collectors.toList());

        // 把收集的collectAttrRespVoList 设置到分页工具中
        pageUtils.setList(collectAttrRespVoList);
        // 返回分页工具
        return pageUtils;
    }

    /**
     * 获取属性分组的关联的所有属性
     * 根根据attrgroupId分组id 查询所有基本属性
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        // 查询属性分组关联的所有信息
        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        // 查询属性处理 收集所有的属性id
        List<Long> collectAttrIdList = relationEntityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        // 查询所有的商品属性
        if (CollectionUtils.isNotEmpty(collectAttrIdList)) {
            List<AttrEntity> attrEntityList = this.listByIds(collectAttrIdList);
            // 返回数据集合
            return attrEntityList;
        } else {
            return null;
        }
    }



}
